package org.v2ray.rocket.proxy.support.utils

import android.app.Activity
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import www.sanju.motiontoast.MotionToast
import www.sanju.motiontoast.MotionToastStyle
import www.sanju.motiontoast.R

// 扩展函数方式
fun Activity.showToast(
    style: MotionToastStyle = MotionToastStyle.SUCCESS,
    title: String? = null,
    message: String?,
    duration: Long = MotionToast.SHORT_DURATION,
    action: (() -> Unit)? = null
) {
    MotionToast.createColorToast(
        this,
        title,
        message ?: "",
        style,
        MotionToast.GRAVITY_BOTTOM,
        duration,
        ResourcesCompat.getFont(this, R.font.helvetica_regular)
    )
    // 延迟执行闭包
    CoroutineScope(Dispatchers.Main).launch {
        delay(duration)
        action?.invoke() // 执行闭包
    }
}

fun Fragment.showToast(
    style: MotionToastStyle = MotionToastStyle.SUCCESS,
    title: String? = null,
    message: String?,
    duration: Long = MotionToast.SHORT_DURATION,
    action: (() -> Unit)? = null
) {
    val mActivity = activity ?: return
    MotionToast.createColorToast(
        mActivity,
        title,
        message ?: "",
        style,
        MotionToast.GRAVITY_BOTTOM,
        duration,
        ResourcesCompat.getFont(
            requireContext(),
            R.font.helvetica_regular
        )
    )
    // 延迟执行闭包
    CoroutineScope(Dispatchers.Main).launch {
        delay(duration)
        action?.invoke() // 执行闭包
    }
}